package com.docMan.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javassist.expr.Cast;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.docMan.dao.BaseDao;
import com.docMan.dao.pojo.DocDirectory;
import com.docMan.dao.pojo.DocFile;
import com.docMan.dao.pojo.DocForward;
import com.docMan.dao.pojo.Tchuman;
import com.docMan.service.DocDirectoryService;
import com.docMan.service.DocFileService;
import com.docMan.service.DocForwardService;
import com.docMan.service.TchumanService;
import com.docMan.utils.CastUtil;
import com.docMan.utils.DocDirectoryUpdate;
import com.docMan.utils.FinalConfig;
import com.docMan.utils.FtpUtils;
import com.docMan.utils.GetRealPath;
import com.docMan.utils.MathUtil;
import com.docMan.utils.ProjectUtils;
import com.docMan.utils.ProperiesUtils;
import com.docMan.utils.PropsUtil;
import com.gqb.websocket.MyWebSocket;

@Service("docForwardService")
public class DocForwardServiceImpl extends BaseServiceImpl<DocForward>
		implements DocForwardService {
	private HttpSession session;
	private TchumanService tchumanService;
	private DocFileService docFileService;
	private DocDirectoryService docDirectoryService;
	@Autowired
	public void setDocDirectoryService(DocDirectoryService docDirectoryService) {
		this.docDirectoryService = docDirectoryService;
	}

	@Autowired
	public void setDocFileService(DocFileService docFileService) {
		this.docFileService = docFileService;
	}

	@Autowired
	public void setTchumanService(TchumanService tchumanService) {
		this.tchumanService = tchumanService;
	}

	@Autowired
	public void setSession(HttpSession session) {
		this.session = session;
	}

	@Resource
	@Override
	public void setDao(BaseDao<DocForward> dao) {
		super.setDao(dao);
	}

	@Override
	@Transactional
	public String forwardFiles(List<Integer> fileIds, List<Integer> unitIds,
			List<Integer> humanIds) {
		try {
			String tempPath = ProperiesUtils.getProperty("docTemp")
					+ FinalConfig.path_split + System.currentTimeMillis()
					+ session.getAttribute(FinalConfig.SESSION_HUMANID)
					+ FinalConfig.path_split;
			// TODO copy file 2 temPath
			List<Tchuman> humans = new ArrayList<Tchuman>();
			List<DocFile> docFiles = new ArrayList<DocFile>();
			HashSet<Integer> toHumanIds = new HashSet<Integer>();
			for (Integer fileId : fileIds) {
				DocFile docFile = docFileService.getById(fileId);
				docFiles.add(docFile);
			}
			if (!downFile2TemPath(docFiles, tempPath)) {
				putFalse();
				putMessage("文件发送出现错误，可能因为源文件不存在");
			}
			for (Integer unitId : unitIds) {
				humans = tchumanService.findNoCache(
						"select h from Tchuman h where h.unitid=?", unitId);
				for (Tchuman human : humans) {
					toHumanIds.add(human.getHumanid());
				}
			}
			for (Integer humanId : humanIds) {
				toHumanIds.add(humanId);
			}

			Iterator<Integer> it = toHumanIds.iterator();
			List<DocForward> docForwards = new ArrayList<DocForward>();
			DocForward docForward = null;
			Integer toHumanId = null;
			while (it.hasNext()) {
				toHumanId = it.next();
				for (DocFile docFile : docFiles) {
					docForward = new DocForward();
					docForward.setFromHumanId(CastUtil.castInt(session
							.getAttribute(FinalConfig.SESSION_HUMANID)));
					docForward.setToHumanId(toHumanId);
					docForward.setCreatTime(new Timestamp(System
							.currentTimeMillis()));
					docForward.setTemPath(tempPath);
					docForward.setFileId(docFile.getId());
					docForward.setFileName(docFile.getFileName());
					docForward.setFromHumanName(session.getAttribute(FinalConfig.SESSION_HUMANNAME).toString());
					docForwards.add(docForward);
				}
			}
			saveOrUpdateAll(docForwards);
			put("fileCount", fileIds.size());
			put("fromHumanName",
					session.getAttribute(FinalConfig.SESSION_HUMANNAME));
			MyWebSocket.push(humanIds, getMap());
		} catch (Exception e) {
			e.printStackTrace();
			putFalse();
			putMessage("文件发送出现错误");
		}
		putSuccess();
		return getMap();
	}

	/**
	 * 将要发送的文件放到临时目录下
	 * 
	 * @param docFiles
	 * @return
	 */
	private boolean downFile2TemPath(List<DocFile> docFiles, String tempPath) {
		String remotePath = null;
		for (DocFile docFile : docFiles) {
			remotePath = GetRealPath.getPath(docFile.getPath());
			if (!FtpUtils.downloadFile(FinalConfig.getDocFtp(),
					docFile.getFileName(), remotePath, tempPath)) {
				return false;
			}
		}
		return true;
	}

	@Override
	public String getHumanUnacceptForward() {

		List<DocForward> docForwards = findNoCache(
				"select f from DocForward f where f.toHumanId=?",
				CastUtil.castInt(session
						.getAttribute(FinalConfig.SESSION_HUMANID)));
		put("forwards", docForwards);
		put("forwardCount", docForwards.size());
		return getMap();
	}

	@Override
	public String deleteUnacceptForward(int forwardId) {
		delete(forwardId);
		putSuccess();
		return getMap();
	}

	@Override
	public String acceptForwardFile(int forwardId, int directoryId) {
		DocForward docForward=getById(forwardId);
		String localPath=docForward.getTemPath()+docForward.getFileName();
		String remotePath=GetRealPath.getDirPath(directoryId);
		DocDirectory docDirectory=docDirectoryService.getById(directoryId);
		List<String> fileSizes=new ArrayList<String>();
		FileInputStream in;
		try {
			in = new FileInputStream(new File(localPath));
			fileSizes.add(MathUtil.fileSize(in.available())+FinalConfig.SIZE_MB);
			DocFile docFile=new DocFile();
			docFile.setFileName(docForward.getFileName());
			docFile.setLarge(CastUtil.castDouble(MathUtil.fileSize(in.available())));
			docFile.setHumanId(Integer.parseInt(session.getAttribute(
					FinalConfig.SESSION_HUMANID).toString()));
			docFile.setHumanName(session.getAttribute(
					FinalConfig.SESSION_HUMANNAME).toString());
			docFile.setImgClass(ProjectUtils.getImgClass(docForward.getFileName()));
			docFile.setDisplayFileName(docForward.getFileName());
			docFile.setDirectoryId(directoryId);
			docFile.setPath(docDirectory.getPath()+FinalConfig.path_split+directoryId);
			docFile.setCreateTime(new Timestamp(System.currentTimeMillis()));
			FtpUtils.uploadFile(FinalConfig.getDocFtp(), docForward.getFileName(), remotePath, in);
			docFileService.save(docFile);
		} catch (IOException e) {
			e.printStackTrace();
			putFalse();
			putMessage("发送过来的文件已经不存在");
			return getMap();
		}
		putSuccess();
		delete(forwardId);
		DocDirectoryUpdate.updateParentsDirectoryWhenAddFiles(fileSizes, directoryId, FinalConfig.FILE_IN_DIRECTORY);
		return getMap();
	}
}
